# -*- coding: utf-8 -*-
"""
****************************
@Time    : 2021/4/28 14:21
@Author  : Candy
@File    : auth.py
****************************
"""
import re
from functools import wraps
from urllib.parse import urlparse

from flask import request, jsonify
from flask_sqlalchemy import SQLAlchemy

from models.auth import AuthUrl
from models.response import MyResponse
from models.users import User
from utils.auth import MiniJWT


def login_and_auth_middleware(func):
    m = MiniJWT()
    results = MyResponse()

    @wraps(func)
    def wrapper(*args, **kwargs):
        token = request.headers.get('token')
        url = urlparse(request.url).path
        ip = request.remote_addr
        ua = request.user_agent
        status, _ = m.check(token, ip, ua.string)
        if status:
            if not url_auth(aid=_, url=url):
                results.code = 201
                results.status = 'error'
                results.results['message'] = '您没有对应的操作权限'
                res = jsonify(results.data())
            else:
                res = func(1, *args, **kwargs)
        else:
            results.code = 201
            results.status = 'error'
            results.results['message'] = '校验失败 登录失效 (可能由于游客模式)'
            res = jsonify(results.data())
        return res
    return wrapper


def url_auth(aid, url):
    db = SQLAlchemy()
    login_user = db.session.query(User).filter(User.is_del == 0).filter(User.id == aid).first()
    auth_url = db.session.query(AuthUrl).filter(AuthUrl.url == url).first()
    return str(bin(login_user.level))[re.search('1', str(bin(auth_url.level))).start()]
